using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.U2D;

namespace Client.Base
{
    public static class Localization
    {
        static public event Action onChange;
        static private readonly Dictionary<string, string> text_dict = new();
        static private readonly Dictionary<string, SpriteAtlas> sprite_dict = new();

        static public string CurLanuage
        {
            get
            {
                return PlayerPrefs.GetString("client_lanuage", "cn");
            }
            set
            {
                PlayerPrefs.SetString("client_lanuage", value);
                PlayerPrefs.Save();
            }
        }

        static public void SetSource(string data)
        {
            ClearText();
            List<CLanguage> ls = JsonConvert.DeserializeObject<List<CLanguage>>(data);
            foreach (CLanguage l in ls)
            {
                text_dict.TryAdd(l.key, l.content);
            }
            onChange?.Invoke();
        }

        static public void SetSource(SpriteAtlas alts)
        {
            sprite_dict.TryAdd(alts.name, alts);
        }

        static public string GetContent(string key)
        {
            if (!text_dict.TryGetValue(key, out var content))
            {
                // LLog.ColorLog(ELogColor.Yellow, $" not exist text:{key}");
            }
            return content;
        }
        

        static public Sprite GetSprite(string atlasName, string spriteName)
        {
            if (!sprite_dict.ContainsKey(atlasName))
            {
               // LLog.ColorLog(ELogColor.Yellow, $" not exist altas:{atlasName}");
                return null;
            }
            return sprite_dict[atlasName].GetSprite(spriteName);
        }

     

        static public void ClearText() => text_dict.Clear();
        static public void ClearAtlas() => text_dict.Clear();

    }
}
